package com.peanut.baby.mvp.login;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.peanut.baby.AppConfig;
import com.peanut.baby.BuildConfig;
import com.peanut.baby.InitManager;
import com.peanut.baby.R;
import com.peanut.baby.http.HttpConfig;
import com.peanut.baby.model.AuthrizeInfo;
import com.peanut.baby.mvp.bind.BindMobileActivity;
import com.peanut.baby.mvp.main.MainActivity;
import com.peanut.baby.mvp.web.WebViewActivity;
import com.peanut.devlibrary.BaseActivity;
import com.peanut.devlibrary.util.StringUtil;
import com.tencent.mars.xlog.Log;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by anonymouslystudio on 2017/7/5.
 */

public class LoginActivity extends BaseActivity implements LoginContract.View, View.OnClickListener {
    private static final String TAG = LoginActivity.class.getSimpleName();
    @BindView(R.id.phone_nubmber_edit)
    EditText mobileEdit;
    @BindView(R.id.identifying_code_edit)
    EditText codeEdit;
    @BindView(R.id.get_vcode)
    TextView getVcode;
    @BindView(R.id.login_submit)
    TextView loginSubmit;
    @BindView(R.id.login_sdk)
    ImageView loginSdk;
    @BindView(R.id.login_logo)
    ImageView loginLogo;
    @BindView(R.id.login_terms)
    TextView loginTerms;
    @BindView(R.id.login_privacy)
    TextView loginPrivacy;

    /**
     * is host request a result
     */
    private boolean requestResult = false;

    private LoginPresenter presenter;

    /**
     * will not return login result
     *
     * @param ctx
     */
    public static void start(Context ctx) {
        Intent intent = new Intent(ctx, LoginActivity.class);
        ctx.startActivity(intent);
    }

    public static void startAndClear(Context ctx) {
        Intent intent = new Intent(ctx, LoginActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        ctx.startActivity(intent);
    }

    /**
     * will return login result
     *
     * @param ctx
     */
    public static void startForResult(Activity ctx) {
        Intent intent = new Intent(ctx, LoginActivity.class);
        intent.putExtra("requestResult", true);
        ctx.startActivityForResult(intent, AppConfig.RequestResult.REQUEST_CODE_LOGIN);
    }


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        ButterKnife.bind(this);
        requestResult = getIntent().getBooleanExtra("requestResult", false);

        presenter = new LoginPresenter(this, this);
        initViews();


    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        presenter.onDestory();
    }

    /**
     *
     */
    private void initViews() {
        getVcode.setOnClickListener(this);
        loginSubmit.setOnClickListener(this);
        loginSdk.setOnClickListener(this);
        loginPrivacy.setOnClickListener(this);
        loginTerms.setOnClickListener(this);
        if (BuildConfig.LOG_DEBUG) {
            loginLogo.setOnClickListener(this);
        }

    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.get_vcode:
                queryVcode();
                break;
            case R.id.login_terms:
                WebViewActivity.start(this, HttpConfig.TERMS_POLICY_URL,"服务协议","");
                break;
            case R.id.login_privacy:
                WebViewActivity.start(this, HttpConfig.PRIVACY_POLICY_URL,"隐私政策","");
                break;
            case R.id.login_submit:
                submitLoginRequest();
                break;
            case R.id.login_logo:
                submitTestLoginRequest();
                break;
            case R.id.login_sdk:
                presenter.wxAuth();
                break;
        }
    }

    @Override
    public void onLoginSuccess() {
        showToast("登陆成功");
        if(!isFinishing()){
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    InitManager.getInstance().uploadPushIdIfNeeded();
                    if (requestResult) {
                        if (StringUtil.isNullOrEmpty(InitManager.getInstance().getUser().mobile)) {
                            BindMobileActivity.startForResult(LoginActivity.this);
                        } else {
                            setResult(RESULT_OK);
                            finish();
                        }

                    } else {
                        if (StringUtil.isNullOrEmpty(InitManager.getInstance().getUser().mobile)) {
                            BindMobileActivity.startForResult(LoginActivity.this);
                        } else {
                            MainActivity.start(LoginActivity.this);
                            finish();
                        }

                    }
                }
            });
        }


    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == AppConfig.RequestResult.REQUEST_CODE_BIND) {
            //when request code is bind mobile ,ignore bind result
            if (requestResult) {
                setResult(RESULT_OK);
                finish();
            } else {
                MainActivity.start(LoginActivity.this);
                finish();
            }
        }
    }

    @Override
    public void onFailed(final String failReason) {
        dismissProgressDialog();
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                showToast(failReason);
                getVcode.setEnabled(true);
                mobileEdit.setEnabled(true);
            }
        });
    }

    @Override
    public void startCountDown() {
        dismissProgressDialog();
        showToast("验证码已发送，请查收！");
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                getVcode.setEnabled(false);
                mobileEdit.setEnabled(false);
            }
        });
    }

    @Override
    public void onCountDown(final int current) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                getVcode.setText(current + "");
            }
        });
    }

    @Override
    public void onCountComplete() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                getVcode.setEnabled(true);
                getVcode.setText("获取验证码");
                mobileEdit.setEnabled(true);
            }
        });
    }


    @Override
    public void onAuthSuccess(final AuthrizeInfo info) {
        Log.d(TAG, "onAuthSuccess ");
        showProgressDialog("正在登录...", false);
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                presenter.submitSdkLogin(info);
            }
        });

    }


    /**
     * 获取验证码
     */
    private void queryVcode() {
//        Log.d(TAG, "MobSdk.getAppKey: " + MobSDK.getAppkey());
        String mobile = mobileEdit.getText().toString();
        if (StringUtil.isNullOrEmpty(mobile) || !StringUtil.isMobile(mobile)) {
            showToast("请输入11位手机号");
            return;
        }
        showProgressDialog("请稍后...", false);
        mobileEdit.setEnabled(false);
        presenter.getVCode(mobile);
    }


    /**
     *
     */
    private void submitLoginRequest() {
        String mobile = mobileEdit.getText().toString();
        String code = codeEdit.getText().toString();
        if (StringUtil.isNullOrEmpty(mobile) || !StringUtil.isMobile(mobile)) {
            showToast("请输入手机号");
            return;
        }
        if (StringUtil.isNullOrEmpty(code)) {
            showToast("请输接收到的验证码");
            return;
        }
        hideSoftKeyboard();
        updateProgressDialog("正在登陆...", false);
        presenter.submitLoginRequest(mobile, code);
    }

    private void submitTestLoginRequest() {
        String mobile = mobileEdit.getText().toString();
        if (StringUtil.isNullOrEmpty(mobile) || !StringUtil.isMobile(mobile)) {
            showToast("请输入手机号");
            return;
        }
        hideSoftKeyboard();

        updateProgressDialog("正在登陆...", false);
        presenter.testLogin(mobile);
    }
}
